//
//  DCRichFileTransferProxy.m
//  LibWeexDCFileTransfer
//
//  Created by simple on 2019/4/10.
//  Copyright © 2019年 simple. All rights reserved.
//

#import "DCRichFileTransferProxy.h"
#import "Utils.h"

@implementation DCRichFileTransferProxy
-(void)onCreateUniPlugin{
    
    NSArray *dirArray = [Utils listDirectory];
    NSLog(@"All folders:%@",dirArray);
    NSLog(@"File下的文件\n");
    for (NSString *file in dirArray) {
        NSLog(@"文件：%@",file);
    }
    
    NSLog(@"11111 有需要初始化的逻辑可以放这里！");
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
    NSLog(@"111111 有需要didFinishLaunchingWithOptions可以放这里！");
    return YES;
}

- (BOOL)application:(UIApplication *_Nullable)application handleOpenURL:(NSURL *_Nullable)url{
    if (url) {
        NSString *fileName = url.lastPathComponent; // 从路径中获得完整的文件名（带后缀）
        
        // path 类似这种格式：file:///private/var/mobile/Containers/Data/Application/83643509-E90E-40A6-92EA-47A44B40CBBF/Documents/Inbox/jfkdfj123a.pdf
        NSString *path = url.absoluteString; // 完整的url字符串
        
        path =(__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL, (__bridge CFStringRef)path, CFSTR(""), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
        NSLog(@"decodedString = %@",path);
        
        NSMutableString *string = [[NSMutableString alloc] initWithString:path];
        
        if ([path hasPrefix:@"file://"]) { // 通过前缀来判断是文件
            // 去除前缀：/private/var/mobile/Containers/Data/Application/83643509-E90E-40A6-92EA-47A44B40CBBF/Documents/Inbox/jfkdfj123a.pdf
            [string replaceOccurrencesOfString:@"file://" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, path.length)];
            
            [self handleFile:string];
            // 此时获取到文件存储在本地的路径，就可以在自己需要使用的页面使用了
            NSDictionary *dict = @{@"fileName":fileName,
                                   @"filePath":string
                                   };
            [[NSNotificationCenter defaultCenter] postNotificationName:@"FileNotification" object:nil userInfo:dict];
            
            
            return YES;
        }
    }
    return YES;
}

- (void)handleFile:(NSString*)path{
    NSData *data = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:path]];
    
    //写入文件到file中
    [self createFileDirectories];
    
    NSString *suff = [path pathExtension];
    NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
    [objDateformat setDateFormat:@"yyyyMMddHHmmssSSS"];
    NSString *name = [objDateformat stringFromDate:[NSDate date]];
    
    name = [[NSFileManager defaultManager] displayNameAtPath:path];//[name stringByAppendingString:[NSString stringWithFormat:@".%@",suff]];
    NSString *newFilePath = [NSString stringWithFormat:@"%@/%@",[Utils newDirector],name];
    BOOL isSuccess =[data writeToFile:newFilePath atomically:TRUE];
    if (isSuccess) {
        [[NSUserDefaults standardUserDefaults] setObject:newFilePath forKey:@"NewFilePath"];
        NSLog(@"保存成功");
    }else{
        NSLog(@"保存失败");
    }
}

- (void)createFileDirectories{
    NSString *filePath = [Utils newDirector];
    // 判断存放音频、视频的文件夹是否存在，不存在则创建对应文件夹
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL isDir = FALSE;
    BOOL isDirExist = [fileManager fileExistsAtPath:filePath isDirectory:&isDir];
    
    NSError *error = nil;
    if(!(isDirExist && isDir))
        
    {
        BOOL bCreateDir = [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:TRUE attributes:nil error:&error];
        if(!bCreateDir){
            
            NSLog(@"Create Audio Directory Failed.");
            
        }
        
        NSLog(@"%@",filePath);
        
    }
}

@end
